<template>
	<view class="page-fade-in" :style="{opacity: pageOpc}">
		<template v-if="pageOpc">
			<view class="content">
				<view class="shop-info-box">
					<view class="info-item flexWrapNo">
						<view>券的名称：</view>
						<input placeholder="请输入名称" placeholder-class="placeholderclass" v-model="title"/>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>面值金额：</view>
							<input placeholder="请输入金额" placeholder-class="placeholderclass" v-model="price" type="digit"/>
						</view>
						<text>元</text>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>使用条件：</view>
							<view style="margin-right: 28rpx;">订单满</view>
							<input placeholder="请输入金额" placeholder-class="placeholderclass" :disabled="type==2" v-model="condition" type="digit"/>
						</view>
						<text>元，可以使用</text>
					</view>
					<view class="info-item flexWrapNo">
						<view>发行总数：</view>
						<input placeholder="请输入数量" placeholder-class="placeholderclass" :disabled="type==2" v-model="num" type="number" />
					</view>
					<view class="remaks-box">
						优惠券发行总数最大允许发行：999999
					</view>
					<view class="info-item flexWrapNo">
						<view>手工发券最大数量：</view>
						<input placeholder="请输入数量" placeholder-class="placeholderclass" type="number" v-model="limits"/>
					</view>
					<view class="remaks-box">
						单次手动发放优惠券的总数最大数量限制，若超过此限制，可选择分次发放
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>有效时间：</view>
							<picker @change="bindPickerChange" :value="index" :range="array">
								<view class="uni-input">{{array[index]}}</view>
							</picker>
						</view>
						<text class="icon-more"></text>
					</view>
					<block v-if="index==1">
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>开始时间：</view>
								<picker mode="date" :data-index='0' :value="starTime" @change="bindDateChange" :start="date">
									<view class="select-input" v-if="starTime">{{starTime}}</view>
									<view class="select-input" v-else>请选择开始时间</view>
								</picker>
							</view>
							<text class="icon-more"></text>
						</view>
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>结束时间：</view>
								<picker mode="date" :data-index='1' :value="date" @change="bindDateChange" :start="starTime">
									<view class="select-input" v-if="endTime">{{endTime}}</view>
									<view class="select-input" v-else>请选择结束时间</view>
								</picker>
							</view>
							<text class="icon-more"></text>
						</view>
					</block>
					<view class="info-item flexWrap" v-if="index==2">
						<view class="flexWrapNo" style="flex: 1;">
							<view>有效天数：</view>
							<input placeholder="请输入天数" placeholder-class="placeholderclass" v-model="valid_configure" type="number" maxlength="5"/>
						</view>
						<text>天</text>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">使用时间限制：</view>
							<picker @change="timeLimitChange" :value="timeLimitIndex" :range="timeLimitArray" range-key="name">
								<view class="uni-input">{{timeLimitArray[timeLimitIndex].name}}</view>
							</picker>
						</view>
						<text class="icon-more"></text>
					</view>
					<view class="info-item flexWrap" v-if="timeLimitIndex!=0">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">时间段：</view>
							<view class="flexWrap">
								<picker mode="time" :value="limitStartTime" start="00:00" end="24:00" :data-index='0'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="limitStartTime">{{limitStartTime}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
								<text class="small">至</text>
								<picker mode="time" :value="limitEndTime" start="00:00" end="24:00" :data-index='1'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="limitEndTime">{{limitEndTime}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
							</view>
						</view>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">适用桌台：</view>
							<picker @change="bindTableChange" :value="tableIndex" :range="tableArray" range-key="name">
								<view class="uni-input">{{tableArray[tableIndex].name}}</view>
							</picker>
						</view>
						<text class="icon-more"></text>
					</view>
					<view class="info-item flexWrapNo">
						<view>适用店铺：</view>
						<view>{{shopname}}</view>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">其他店铺：</view>
							<view class="select-input" @tap="openAttr">
							    {{shopValue || '请选择'}}
							</view>
						</view>
						<text class="icon-more"></text>
					</view>	
				</view>
				<view class="determine-btn" @tap="couponEdit">提交保存</view>
				<niceui-popup-select ref="showAttr" :columns="selectMultipleColumns" :selectValue="use_store_ids"
				         :option="{label:'shop_name', value:'id'}" @confirm="confirmAttr"></niceui-popup-select>			
			</view>
		</template>
	</view>
</template>

<script>
	export default {
		data() {
			const currentDate = this.getDate({
				format: true
			})
			const starDate = this.getDate('start')
			return {
				pageOpc: 0,
				array: ['永久有效', '指定日期', '指定天数'],
				index: 0,
				starTime: starDate,
				endTime: currentDate,
				date: currentDate,
				title:"",
				price:"",
				condition:"",
				num:"",
				limits:"",
				valid_configure:"",
				weekdata:"1,2,3,4,5,6,7",
				content:"老板端录入",
				couponId:"",
				couponInfo:{},
				shopname:"",
				type:1,
				timeLimitArray:[
					{
						name:'全部时间可用',
						value:'unlimited'
					},
					{
						name:'指定时间段可用',
						value:'limit'
					},
					{
						name:'指定时间段不可用',
						value:'appoint_unavailable'
					}
				],
				timeLimitIndex:0,
				limitStartTime:'',
				limitEndTime:'',
				
				tableArray:[
					{name:'全部',value:'0'},
					{name:'乒乓球',value:'1'}
				],
				tableIndex:0,
				usable_table_type:0,
				selectMultipleShow:false,
				selectMultipleColumns:[],
				shopValue: '',
				shopIndex: [],
				single_purchase_limit_data:"unlimited",
				use_store_ids:[]
			}
		},
		onLoad(ops) {
			this.couponId=ops.couponId||""
			if(this.couponId) this.getCouponInfo()
			else this.getStoreList()
			this.shopname=uni.getStorageSync('shopname')
			console.log(this.shopname)
		},
		onReady() {
			setTimeout(() => {
				this.pageOpc = 1
			}, 100)
		},
		methods: {
			// 获取优惠券信息
			getCouponInfo(){
				this.$request.post(this.$api.couponInfo, {
					store_id:uni.getStorageSync('store_id'),
					coupon_id:this.couponId
				}, {
					token:true
				}).then(res => {
					let {
						data = {}
					} = res;
					if (res.code==1) {
						this.couponInfo=data
						if(data.valid_timedata==2){
							data.valid_configure = data.valid_configure.replace(/-/g,"/");
							let customTimeArr=data.valid_configure.split(' / ')
							let start=customTimeArr[0]
							let end=customTimeArr[1]
							data.start=this.$tools.formatDay(start)
							data.end=this.$tools.formatDay(end)
							this.starTime=data.start
							this.endTime=data.end
						}else{
							this.valid_configure=data.valid_configure
						}
						this.limitIndex=this.couponInfo.date_limit_data=="whole"?0:1
						this.timeLimitIndex=this.timeLimitArray.findIndex((item)=>item.value==this.couponInfo.single_purchase_limit_data)
						this.usable_table_type=this.couponInfo.usable_table_type
						this.tableIndex=this.tableArray.findIndex((item)=>item.value==this.usable_table_type)
						this.single_purchase_limit_data=this.couponInfo.single_purchase_limit_data
						this.limitStartTime=this.couponInfo.purchase_quantity?this.couponInfo.purchase_quantity.start_time:""
						this.limitEndTime=this.couponInfo.purchase_quantity?this.couponInfo.purchase_quantity.end_time:""
						this.couponInfo.purchase_quantity=this.couponInfo.purchase_quantity?this.couponInfo.purchase_quantity:{},
						this.use_store_ids=this.couponInfo.use_store_ids.split(',')
						this.use_store_ids=this.use_store_ids.map(it=>Number(it))
						console.log(this.use_store_ids)
						this.title=data.title
						this.price=data.price
						this.condition=data.condition
						this.num=data.num
						this.limits=data.limits
						this.type=data.type
						this.index=Number(data.valid_timedata-1)
						this.getStoreList();
					}
				})
			},
			getStoreList(){
				this.$request.post(this.$api.getStoreList, {
					usable_table_type:this.usable_table_type,
					store_id:uni.getStorageSync('store_id'),
				}, {
					token:true
				}).then(res => {
					let {
						data = {}
					} = res;
					if (res.code==1) {
						this.selectMultipleColumns=data.store_list
						let shopValue=[]
						for (var i = 0; i <this.selectMultipleColumns.length; i++) {
							for (var j = 0; j <this.use_store_ids.length; j++) {
								if (this.use_store_ids[j]==this.selectMultipleColumns[i].id) {
									shopValue.push(this.selectMultipleColumns[i].shop_name)
								}
							}
						}
						this.shopValue=shopValue.join(',')
					}
				})
			},
			// 新建、修改优惠券
			couponEdit(){
				if(this.type==3){
					this.$tools.showToast('该类型的券不支持修改');
					return;
				}
				if(!this.title){
					this.$tools.showToast('请填写优惠券名称');
					return;
				}else if(!this.price){
					this.$tools.showToast('请填写优惠券金额');
					return;
				}else if(!this.condition){
					this.$tools.showToast('请填写使用金额');
					return;
				}else if(!this.num){
					this.$tools.showToast('请填写优惠券数量');
					return;
				}else if(this.num>999999){
					this.$tools.showToast('最大允许发行：999999');
					return;
				}else if(!this.limits){
					this.$tools.showToast('请填写手工发券最大数量');
					return;
				}else if(Number(this.limits)>Number(this.num)){
					this.$tools.showToast('手工发券最大数量不能大于发行总数');
					return;
				}else if(this.index==2&&!this.valid_configure){
					this.$tools.showToast('请填写有效天数');
					return;
				}
				let requestUrl=""
				if(this.couponId){
					requestUrl=this.$api.couponEdit
				}else{
					requestUrl=this.$api.couponAdd
				}
				let purchase_quantity={
					start_time:this.limitStartTime,
					end_time:this.limitEndTime
				}
				
				if(this.use_store_ids.findIndex(item=>item==uni.getStorageSync('store_id'))==-1){
					this.use_store_ids.push(uni.getStorageSync('store_id'))
				}
				purchase_quantity=JSON.stringify(purchase_quantity)
				this.$request.post(requestUrl, {
					store_id:uni.getStorageSync('store_id'),
					title:this.title,
					price:this.price,
					condition:this.condition,
					num:this.num,
					limits:this.limits,
					valid_timedata:Number(this.index)+1,
					valid_configure:this.index==2?this.valid_configure:this.starTime+' 00:00:00 - '+this.endTime+' 23:59:59',
					weekdata:this.weekdata,
					content:this.content,
					id:this.couponId,
					purchase_quantity:purchase_quantity,
					single_purchase_limit_data:this.single_purchase_limit_data,
					usable_table_type:this.usable_table_type,
					use_store_ids:this.use_store_ids.join(',')
				}, {
					token:true
				}).then(res => {
					let {
						data = {}
					} = res;
					if (res.code==1) {
						this.$tools.showToast('操作成功');
						setTimeout(()=>{
							uni.navigateBack()
						},1000)
					}
				})
			},
			// 获取日期
			getDate(type) {
				const date = new Date();
				date.setDate(date.getDate());
				// if (type === 'start') {
				// 	date.setDate(date.getDate());
				// }
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindPickerChange: function(e) {
				this.index = e.detail.value
				if(this.index==2){
					this.valid_configure=""
				}else{
					this.valid_configure=this.couponInfo.valid_configure
				}
			},
			// 选择日期
			bindDateChange(e) {
				let index = e.currentTarget.dataset.index
				if (index == 0) {
					this.starTime = e.target.value
				} else {
					this.endTime = e.target.value
				}
			},
			
			timeLimitChange(e){
				this.timeLimitIndex = e.detail.value
				this.single_purchase_limit_data=this.timeLimitArray[this.timeLimitIndex].value
			},
			
			// 选择时间
			bindTimeChange(e) {
				let index=e.target.dataset.index
				if(index==0){
					this.limitStartTime=e.target.value
				}else{
					this.limitEndTime=e.target.value
				}		
			},
			
			bindTableChange(e){
				this.tableIndex = e.detail.value
				this.usable_table_type=this.tableIndex
				this.getStoreList();
			},
			openAttr(){
				 this.$refs.showAttr.showPopup()
			},
			confirmAttr(value,data) {
			  console.log(value,data)
			  this.use_store_ids = value
			  let shopValue=[]
			  for (var i = 0; i <this.selectMultipleColumns.length; i++) {
			  	for (var j = 0; j <this.use_store_ids.length; j++) {
			  		if (this.use_store_ids[j]==this.selectMultipleColumns[i].id) {
			  			shopValue.push(this.selectMultipleColumns[i].shop_name)
			  		}
			  	}
			  }
			  this.shopValue=shopValue.join(',')
			  console.log(this.shopValue)
			  this.$refs.showAttr.closePopup()
			},
		}
	}
</script>

<style lang="scss">
	.content {
		padding: 0 30upx;
		overflow: hidden; // 解除BFC问题
		.shop-info-box {
			.info-item {
				font-size: 28upx;
				font-family: PingFang SC;
				font-weight: 400;
				line-height: 40upx;
				color: #FFFFFF;
				padding: 30upx 0;
				border-bottom: 1upx solid #36355E;
				.small {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFFFFF;
					margin: 0 40upx;
				}
				picker{
					flex: 1;
				}
				.select-input{
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
					flex: 1;
				}
				input {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
					flex: 1;
				}

				.icon-more {
					border-color: #FFFFFF;
				}

				.placeholderclass {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
				}
			}
			.remaks-box{
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #82819B;
				line-height: 40rpx;
				padding-left: 138upx;
				margin-top: 12upx;
			}
		}
		.determine-btn{
			font-size: 32rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			width: 322rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #26BCFD;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			margin: 78upx auto;
		}
	}
</style>
